package com.smashcrush.client.gwt.client.editor;

import java.util.Map;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.gen2.table.override.client.FlexTable;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.smashcrush.client.gwt.Images;
import com.smashcrush.model.ScriptResults;


public class ScriptProgress extends DialogBox {

	VerticalPanel dialogContents = new VerticalPanel();

//	ProgressBar bar;

	FlexTable table;

	Command onCloseCommand;

	Button cancelButton;
	
	public ScriptProgress() {
		setText("Running...");

		dialogContents.setSpacing(4);
		setWidget(dialogContents);

		Images im = GWT.create(Images.class);
		Image i = im.loader().createImage();
		dialogContents.add(i);
		
//		bar = new ProgressBar();
//		bar.setWidth("200px");
//		dialogContents.add(bar);

		table = new FlexTable();
		dialogContents.add(table);
		
		cancelButton = new Button("Cancel", new ClickHandler() {
			public void onClick(ClickEvent event) {
				cancel();
			}
		});
		dialogContents.add(cancelButton);
		dialogContents.setCellHorizontalAlignment(cancelButton,
				HasHorizontalAlignment.ALIGN_CENTER);
	}

	public void setOnCloseCommand(Command onClose) {
		onCloseCommand = onClose;
	}

	public void setText(String text) {
		super.setText(text);
	}

//	public void setProgress(double progress) {
//		bar.setProgress(progress);
//	}

	public void setResults(ScriptResults scriptResults) {
		Map<String, String> results = scriptResults.getResults();

		int row = 0;
		for (String key : results.keySet()) {
			table.setText(row, 0, key);
			table.setText(row, 1, results.get(key));
			row++;
		}
	}
	
	public void setError(String error) {

		dialogContents.clear();

		dialogContents.add(new Label(error));

		Button closeButton = new Button("Close", new ClickHandler() {
			public void onClick(ClickEvent event) {
				close();
			}
		});
		dialogContents.add(closeButton);
		dialogContents.setCellHorizontalAlignment(closeButton,
				HasHorizontalAlignment.ALIGN_CENTER);
	}	

	private void cancel() {
		// TODO: AsyncCall
		{System.out.println("cancel!!");
			close();
		}

	}

	private void close() {
		onCloseCommand.execute();
		hide();
	}

}
